<template>
  <div class="syn-create-page">
    <!-- 顶部 -->
    <div class="page-header">
      <a-button type="link" class="back" @click="goBack">
        <LeftOutlined class="back-icon" />
        返回
      </a-button>
      <span class="sep">|</span>
      <span class="title">{{ pageTitle }}</span>
    </div>

    <!-- 新增父级 -->
    <div class="content-area">
      <!-- 表单 -->
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ style: 'width: 88px;' }"
        :wrapper-col="{ style: 'max-width: 720px;' }"
        class="form"
      >
        <!-- 敏感词 -->
        <a-form-item label="敏感词：" name="word">
          <a-input v-model:value="form.word" placeholder="请输入" allow-clear />
        </a-form-item>

        <!-- 启用状态 -->
        <a-form-item label="启用状态：">
          <a-radio-group v-model:value="form.enabled">
            <a-radio :value="true">启用</a-radio>
            <a-radio :value="false">停用</a-radio>
          </a-radio-group>
        </a-form-item>

        <!-- 一级分类 -->
        <a-form-item label="一级分类：" name="cat1Id">
          <a-select
            v-model:value="form.cat1Id"
            :options="cat1Options"
            :loading="cat1Loading"
            placeholder="请选择"
            allow-clear
            style="width: 100%"
          />
        </a-form-item>

        <!-- 二级分类 -->
        <a-form-item label="二级分类：" name="cat2Id">
          <a-select
            v-model:value="form.cat2Id"
            :options="cat2Options"
            :loading="cat2Loading"
            placeholder="请选择"
            allow-clear
            style="width: 100%"
            :disabled="!form.cat1Id"
          />
        </a-form-item>

        <!-- 匹配方式 -->
        <a-form-item label="匹配方式：">
          <a-select
            v-model:value="form.matchMode"
            :options="matchModeOptions"
            disabled
          />
        </a-form-item>

        <!-- 处理方式 -->
        <a-form-item label="处理方式：" name="handleMode">
          <a-select
            v-model:value="form.handleMode"
            :options="handleModeOptions"
            placeholder="请选择处理方式"
            allow-clear
            style="width: 100%"
          />
        </a-form-item>
      </a-form>

      <!-- 底部 -->
      <div class="page-footer">
        <div class="footer-inner">
          <a-button type="link" class="cancel-btn" @click="goBack"
            >取消</a-button
          >
          <span class="sep">|</span>
          <a-button
            type="link"
            class="ok-btn"
            :loading="submitting"
            @click="onSubmit"
            >确定</a-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { LeftOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import type { FormInstance } from "ant-design-vue";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  listFirstNodes,
  listSecondNodesByFirstCodeStrict,
  createSensativeWord,
  updateSensativeWord,
} from "@/api/modules/sensativeWords.api";

type Mode = "add" | "edit";

/** 表单 */
type Payload = {
  word: string;
  enabled: boolean;
  cat1Id?: string | number;
  cat2Id?: string | number;
  matchMode?: "contain";
  handleMode?: "过滤" | "删除";
};

const DEFAULT_TAB = "sensitive";
const route = useRoute();
const router = useRouter();
const mode = ref<Mode>("add");
const editId = ref<string | number | null>(null);

const formRef = ref<FormInstance>();
const submitting = ref(false);

const form = reactive<Payload>({
  word: "",
  enabled: true,
  cat1Id: undefined,
  cat2Id: undefined,
  matchMode: "contain",
  handleMode: undefined,
});

const rules = {
  word: [{ required: true, message: "请输入敏感词" }],
  handleMode: [{ required: true, message: "请选择处理方式" }],
};

const pageTitle = computed(() => (mode.value === "add" ? "新增" : "编辑"));
const currentTab = computed(() => (route.query.tab as string) || DEFAULT_TAB);

/** 下拉选项 */
type Opt = { label: string; value: string | number };
const cat1Options = ref<Opt[]>([]);
const cat1Loading = ref(false);
const cat2Options = ref<Opt[]>([]);
const cat2Loading = ref(false);

/** 固定为“包含匹配” */
const matchModeOptions = [{ label: "包含匹配", value: "contain" as const }];

const handleModeOptions = [
  { label: "过滤", value: "过滤" },
  { label: "删除", value: "删除" },
];

/** 加载一级分类 */
async function loadCat1Options() {
  cat1Loading.value = true;
  try {
    const { data = [] } = await listFirstNodes({
      fields: ["id", "first_query"],
      limit: 1000,
      sort: "id",
    });
    cat1Options.value = data
      .map((it: any) => ({
        value: it.id,
        label: String(it?.first_query ?? "").trim(),
      }))
      .filter((o: Opt) => !!o.label);
  } catch (e: any) {
    message.error(e?.message || "加载一级分类失败");
  } finally {
    cat1Loading.value = false;
  }
}

/** 加载二级分类 */
async function loadCat2Options() {
  cat2Loading.value = true;
  try {
    if (!form.cat1Id) {
      cat2Options.value = [];
      form.cat2Id = undefined;
      return;
    }
    const { data = [] } = await listSecondNodesByFirstCodeStrict({
      firstCodeId: form.cat1Id,
      limit: 1000,
      fields: ["id", "second_query"],
      sort: ["id"],
    });
    cat2Options.value = data
      .map((it: any) => ({
        value: it.id,
        label: String(it?.second_query ?? "").trim(),
      }))
      .filter((o: Opt) => !!o.label);

    // 若当前已选二级不在新数据中，则清空
    if (
      form.cat2Id &&
      !cat2Options.value.some((o) => o.value === form.cat2Id)
    ) {
      form.cat2Id = undefined;
    }
  } catch (e: any) {
    message.error(e?.message || "加载二级分类失败");
  } finally {
    cat2Loading.value = false;
  }
}

/** 编辑 */
async function initByRoute() {
  const m = (route.query.mode as string) || "add";
  mode.value = m === "edit" ? "edit" : "add";

  resetForm();
  editId.value = null;

  if (mode.value !== "edit" || !route.query.row) return;

  try {
    const row = JSON.parse(decodeURIComponent(String(route.query.row)));

    editId.value = row.id;
    form.word = row.name ?? row.sensative_word ?? "";
    form.enabled =
      (row.status ?? "").toLowerCase() === "enabled" ||
      (row.status ?? "").toLowerCase() === "published";
    form.matchMode = "contain";
    form.handleMode = (row.handleMode ?? row.sensative_type) as
      | "过滤"
      | "删除"
      | undefined;

    form.cat1Id =
      row.firstcode?.id ?? row.first_code ?? row.firstcode ?? undefined;
    form.cat2Id =
      row.secondnode?.id ?? row.second_code ?? row.secondnode ?? undefined;

    // 没有 id 但有名称时，通过选项映射
    if (!form.cat1Id && row.category1) {
      const hit = cat1Options.value.find((o) => o.label === row.category1);
      form.cat1Id = hit?.value;
    }

    await loadCat2Options();

    if (!form.cat2Id && row.category2) {
      const hit2 = cat2Options.value.find((o) => o.label === row.category2);
      form.cat2Id = hit2?.value;
    }
  } catch {
    /* ignore */
  }
}

function resetForm() {
  form.word = "";
  form.enabled = true;
  form.cat1Id = undefined;
  form.cat2Id = undefined;
  form.matchMode = "contain";
  form.handleMode = undefined;
  formRef.value?.clearValidate();
}

onMounted(async () => {
  await loadCat1Options();
  await initByRoute();
  await loadCat2Options();
});

/** 一级切换 联动加载二级 */
watch(
  () => form.cat1Id,
  () => loadCat2Options()
);

/** 路由变化回填 */
watch(
  () => [route.query.mode, route.query.row],
  () => initByRoute()
);

/** 返回 */
function goBack() {
  if ((route.query.backTo as string) === "tab") {
    router.push({ path: "/", query: { tab: currentTab.value } });
  } else {
    router.push({
      path: "/sensitiveLexiconTab",
      query: { tab: currentTab.value },
    });
  }
}

/** 提交 */
async function onSubmit() {
  try {
    submitting.value = true;
    await formRef.value?.validate();

    const params = {
      sensative_word: form.word.trim(),
      status: form.enabled ? "published" : "draft",
      sensative_type: form.handleMode!,
      firstcode: form.cat1Id ?? null,
      secondnode: form.cat2Id ?? null,
    };

    if (mode.value === "add") {
      await createSensativeWord(params as any);
      message.success("新增成功");
    } else if (editId.value != null) {
      await updateSensativeWord(editId.value, params as any);
      message.success("保存成功");
    }

    goBack();
  } finally {
    submitting.value = false;
  }
}
</script>

<style lang="less" scoped>
@pad-x: 24px;
@label-w: 88px; 
@wrap-max: 720px;

.syn-create-page {
  --safe-bottom: env(safe-area-inset-bottom);

  position: relative;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  min-height: 100dvh;
  height: 100%;
  box-sizing: border-box;
  overflow: hidden;

  font-family: "PingFang SC", -apple-system, BlinkMacSystemFont, "Segoe UI",
    Roboto, "Helvetica Neue", Arial, sans-serif;

  :deep(.ant-*) {
    font-family: inherit;
  }

  /* 顶部区域 */
  .page-header {
    flex: 0 0 auto;
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 24px 0;

    .back.ant-btn {
      display: inline-flex;
      align-items: center;
      padding-left: @pad-x;
      height: 24px;
      color: #81889c;

      .back-icon {
        font-size: 16px;
      }
    }

    .sep {
      color: #d9d9d9;
    }
    .title {
      font-size: 16px;
      font-weight: 500;
      color: #000;
    }
  }

  /* 新父级 */
  .content-area {
    flex: 1 1 auto;
    min-height: 0;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    overflow-x: hidden;
    -webkit-overflow-scrolling: touch;
    overscroll-behavior: contain;

    /* 自定义滚动条 */
    &::-webkit-scrollbar {
      width: 10px;
      height: 10px;
    }
    &::-webkit-scrollbar-thumb {
      background: rgba(0, 0, 0, 0.15);
      border-radius: 6px;
      border: 2px solid transparent;
      background-clip: padding-box;
    }
    &::-webkit-scrollbar-thumb:hover {
      background: rgba(0, 0, 0, 0.25);
    }
    &::-webkit-scrollbar-track {
      background: transparent;
    }
    scrollbar-width: thin;
    scrollbar-color: rgba(0, 0, 0, 0.25) transparent;
    scrollbar-gutter: stable;
    padding-bottom: calc(16px + var(--safe-bottom));
  }

  /* 表单 */
  .form {
    padding: 24px @pad-x 0 (@pad-x + @label-w);

    :deep(.ant-form-item) {
      margin-bottom: 24px;
    }
    :deep(.ant-form-item-label) {
      display: flex;
      align-items: center;
    }
    :deep(.ant-form-item-label > label) {
      height: 24px;
      line-height: 24px;
      font-size: 14px;
    }
    :deep(.ant-form-item-control) {
      min-height: 24px;
    }
  }

  /* 底部操作栏 */
  .page-footer {
    position: static;
    margin-top: 16px;
    padding: 12px @pad-x calc(12px + var(--safe-bottom)) @pad-x;
    background: #fff;
    border-top: 1px solid #f0f0f0;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.03);

    .footer-inner {
      max-width: @wrap-max;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: center; 
      gap: 12px;
      flex-wrap: wrap;
      width: 100%;
    }

    .sep {
      color: #e5e7eb;
      user-select: none;
      line-height: 24px;
      height: 24px;
      display: inline-flex;
      align-items: center;
      margin: 0 2px;
    }

    /* 优化按钮视觉 */
    .cancel-btn {
      height: 36px;
      padding: 0 16px;
      border-radius: 8px;
      background: #fafafa !important;
      border: 1px solid #e8e8e8 !important;
      color: #666 !important;
      transition: all 0.2s ease;
    }
    .cancel-btn:hover {
      background: #fff !important;
      color: #595959 !important;
      border-color: #d9d9d9 !important;
    }

    .ok-btn {
      height: 36px;
      padding: 0 20px;
      border-radius: 8px;
      font-weight: 600;
      background: #1677ff !important;
      border: 1px solid #1677ff !important;
      color: #fff !important;
      transition: box-shadow 0.2s ease, filter 0.2s ease;
    }
    .ok-btn:hover {
      filter: brightness(1.02);
      box-shadow: 0 2px 8px rgba(22, 119, 255, 0.2);
    }
    .ok-btn[disabled],
    .ok-btn[disabled]:hover {
      background: #69b1ff !important;
      border-color: #69b1ff !important;
      box-shadow: none;
      color: #fff !important;
      opacity: 0.85;
    }
  }

  .top-divider,
  .bottom-divider,
  .footer-placeholder {
    display: none;
  }

  /* 小屏优化 */
  @media (max-width: 576px) {
    .page-header {
      padding: 16px 0;
    }
    .form {
      padding: 16px 12px 0 12px;
    }
    .page-footer {
      padding-left: 12px;
      padding-right: 12px;
    }
  }
}
</style>
